<?php

namespace Lowpress\PressExtensionsBundle\Feeds;

use Lowpress\PressBundle\Feeds\IFeedGatherer;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Lowpress\PressExtensionsBundle\Entity\Pinboard;

class PinboardFeedGatherer implements IFeedGatherer
{


  private $username;
  private $password;

  public function __construct($username, $password)
  {
    $this->username = $username;
    $this->password = $password;
  }

  public function gather(ContainerInterface $container)
  {
    $doctrine = $container->get("doctrine");
    $pinboard_repository = $doctrine->getRepository('LowpressPressExtensionsBundle:Pinboard');
    $em = $doctrine->getEntityManager();
    $last_pinboard = $pinboard_repository->findOneBy(array(), array('created', 'DESC'));


    $f = new \DOMDocument();
    $f->load("https://".$this->username.":".$this->password."@api.pinboard.in/v1/posts/recent");
    foreach ($f->getElementsByTagName("post") as $p)
    {
      $date = new \DateTime($p->getAttribute("time"));
      if (!$last_pinboard || ($last_pinboard && $date > $last_pinboard->getCreated()))
      {
        $pinboard = new Pinboard();
        $pinboard->setHref($p->getAttribute("href"));
        $pinboard->setCreated($date);
        $pinboard->setDescription($p->getAttribute("description"));

        foreach (explode(" ", $p->getAttribute("tag")) as $tag_name)
        {
          if (!empty($tag_name))
          {
            $tag = $doctrine->getRepository('LowpressPressBundle:Tag')->findOneByName($tag_name);
            if ($tag == null)
            {
              $tag = new \Lowpress\PressBundle\Entity\Tag();
              $tag->setName($tag_name);
              $pinboard->addTag($tag);
            }
            $em->persist($tag);
          }
        }
        $em->persist($pinboard);
      }
    }
    $em->flush();
  }

}

?>